const multer = require("multer")
const path = require('path')
const fs = require('fs')
const { HOST } = require('../config/server')
//  配置文件【接收器】仓库
const uploader = multer({
    storage: multer.diskStorage({
        destination(req, file, callback) {
            callback(null, './public/avatar')
        },
        filename(req, file, callback) {
            callback(null, `${file.fieldname + '_' + req.auth.username}${path.extname(file.originalname)}`)
        }
    })
})

// 处理上传的资源是否合法
async function verifyUpload(req, res, next) {
    let extname = path.extname(req.file.filename)
    extname = extname.slice(1).toUpperCase()
    // console.log(extname);
    //  判断上传文件类型
    if (extname != 'JPG' && extname != 'JPEG' && extname != 'PNG') {
        // 删除文件
        fs.unlink('./public/avatar/' + req.file.filename, () => { })
        res.send({
            code: 500,
            message: '禁止上传非图片资源！'
        })
        return
    }
    //  判断上传文件文件大小
    if (req.file.size / 100 > 5000) {
        // 删除文件
        fs.unlink('./public/avatar/' + req.file.filename, () => { })
        res.send({
            code: 500,
            message: '禁止上传大于5MB的图片资源！'
        })
        return
    }
    // 头像url
    req.avatarUrl = HOST + '/public/avatar/' + req.file.filename
    next()
}

module.exports = {
    uploader,
    verifyUpload
}